import { defineStore } from 'pinia'
import { invoke } from '@tauri-apps/api/core' 
import { getStore } from './pinia'
import { withRetry } from '../utils/retry.js'

// 预测模块
export const usePredictionStore = defineStore('prediction', {
  state: () => ({
    predictions: {},
    confidenceScores: {},
    predictionMetrics: {},
  }),
  actions: {
    // 获取股票数据的辅助方法
    async fetchStockData(symbol, timeframe = 'daily') {
      try {
        // 调用后端获取股票数据
        const data = await invoke('get_stock_data', { 
          symbol, 
          timeframe,
          limit: 100 // 获取最近100条数据
        });
        return data;
      } catch (error) {
        console.error('Error fetching stock data:', error);
        throw error;
      }
    },
    
    async getPrediction(symbol, timeframe = 'daily') {
      try {
        // 首先获取股票数据
        const stockData = await this.fetchStockData(symbol, timeframe);
        
        console.log('调用 handle_unified_prediction，参数:', { action: 'predict', params: { stock_code: symbol, timeframe, data: stockData } })
        // 确保数据结构正确，并且使用JSON.stringify确保数据可以被序列化
        const cleanData = JSON.parse(JSON.stringify(stockData));
        
        const response = await invoke('handle_unified_prediction', { 
          request: { 
            action: 'predict', 
            params: { 
              stock_code: symbol,
              timeframe: timeframe,
              data: cleanData,
              use_gpu: false // 添加默认值，避免undefined
            } 
          } 
        })
        console.log('handle_unified_prediction 结果:', response)
        if (response.status === 'success' && response.data) {
          this.predictions = { ...this.predictions, [symbol]: response.data }
          return response.data
        } else {
          throw new Error(response.message || 'Prediction failed')
        }
      } catch (error) {
        console.error('Error fetching prediction:', error)
        throw error
      }
    },
    async getPredictionMetrics(symbol) {
      try {
        const result = await invoke('get_prediction_metrics', { symbol })
        this.predictionMetrics = { ...this.predictionMetrics, [symbol]: result }
        return result
      } catch (error) {
        console.error('Error fetching prediction metrics:', error)
        throw error
      }
    },
    async updateConfidenceScore(symbol, score) {
      this.confidenceScores = { ...this.confidenceScores, [symbol]: score }
    },
  },
})

export const useAsyncState=(asyncFunc)=> {
  const data = ref(null)
  const loading = ref(false)
  const error = ref(null)

  async function execute(...args) {
    loading.value = true
    error.value = null
    try {
      data.value = await asyncFunc(...args)
    } catch (err) {
      error.value = err
      console.error('获取数据失败:', err)
    } finally {
      loading.value = false
    }
  }

  return { data, loading, error, execute }
}

// 市场数据模块
export const useMarketDataStore = defineStore('marketData', {
  state: () => ({
    realTimeData: {},
    historicalData: {},
  }),
  actions: {
    async getRealTimeData(symbol) {
      try {
        const result = await invoke('get_realtime_data', { symbol })
        this.realTimeData = { ...this.realTimeData, [symbol]: result }
      } catch (error) {
        console.error('Error fetching real-time data:', error)
        throw error
      }
    },
    async getHistoricalData(_params) {
      try {
        // 确保参数中包含 timeframe，默认为 '1d'
        const params = {
          ..._params
        };
        const result = await invoke('get_historical_data', { params })
        this.historicalData = { ...this.historicalData, [_params.symbol]: result }
        return result;
      } catch (error) {
        console.error('Error fetching historical data:', error)
        throw error
      }
    },
  },
})

// 系统配置模块
export const useSystemConfigStore = defineStore('systemConfig', {
  state: () => ({
    config: null,
  }),
  actions: {
    async getSystemConfig() {
      try {
        this.config = await invoke('get_system_config')
      } catch (error) {
        console.error('Error fetching system config:', error)
        throw error
      }
    },
    async updateSystemConfig(config) {
      try {
        await invoke('update_system_config', { config })
        await this.getSystemConfig()
      } catch (error) {
        console.error('Error updating system config:', error)
        throw error
      }
    },
  },
})

// 模型训练模块
export const useModelTrainingStore = defineStore('modelTraining', {
  state: () => ({
    trainingStatus: null,
  }),
  actions: {
    async runModelTraining(config) {
      try {
        await invoke('run_model_training', { config })
      } catch (error) {
        console.error('Error running model training:', error)
        throw error
      }
    },
    async getTrainingStatus(taskId) {
      try {
        this.trainingStatus = await invoke('get_training_status', { taskId })
      } catch (error) {
        console.error('Error fetching training status:', error)
        throw error
      }
    },
  },
})

// AI评估模块
export const useAIEvaluationStore = defineStore('aiEvaluation', {
  state: () => ({
    evaluations: {},
  }),
  actions: {
    async getAIEvaluation(symbol) {
      try {
        const result = await invoke('get_ai_evaluation', { symbol })
        this.evaluations = { ...this.evaluations, [symbol]: result }
      } catch (error) {
        console.error('Error fetching AI evaluation:', error)
        throw error
      }
    },
  },
})

// 策略构建模块
export const useStrategyBuilderStore = defineStore('strategyBuilder', {
  state: () => ({
    strategies: [],
  }),
  actions: {
    async createStrategy(strategy) {
      try {
        const result = await invoke('create_strategy', { strategy })
        this.strategies.push(result)
      } catch (error) {
        console.error('Error creating strategy:', error)
        throw error
      }
    },
    async getStrategies() {
      try {
        this.strategies = await invoke('get_strategies')
      } catch (error) {
        console.error('Error fetching strategies:', error)
        throw error
      }
    },
  },
})

// 回测模块
export const useBacktestStore = defineStore('backtest', {
  state: () => ({
    backtestResults: {},
  }),
  actions: {
    async runBacktest(params) {
      try {
        const result = await invoke('run_backtest', params)
        this.backtestResults = { ...this.backtestResults, [params.strategyId]: result }
      } catch (error) {
        console.error('Error running backtest:', error)
        throw error
      }
    },
  },
})

// 市场情绪分析模块
export const useMarketSentimentStore = defineStore('marketSentiment', {
  state: () => ({
    sentimentData: null,
    marketIndices: [],
    marketNews: [],
  }),
  actions: {
    async getMarketSentiment() {
      try {
        this.sentimentData = await invoke('get_market_sentiment')
        return this.sentimentData
      } catch (error) {
        console.error('Error fetching market sentiment:', error)
        throw error
      }
    },
    async getMarketIndices() {
      try {
        this.marketIndices = await invoke('get_market_indices')
        return this.marketIndices
      } catch (error) {
        console.error('Error fetching market indices:', error)
        throw error
      }
    },
    async getMarketNews() {
      try {
        this.marketNews = await invoke('get_market_news')
        return this.marketNews
      } catch (error) {
        console.error('Error fetching market news:', error)
        throw error
      }
    },
    async getMarketSentimentIndicators() {
      try {
        return await invoke('get_market_sentiment_indicators')
      } catch (error) {
        console.error('Error fetching market sentiment indicators:', error)
        throw error
      }
    },
    async getMarketHeatmapData(timeRange) {
      try {
        return await invoke('get_market_heatmap_data', { timeRange })
      } catch (error) {
        console.error('Error fetching market heatmap data:', error)
        throw error
      }
    },
  },
})

// 主 store
export const useAITradeStore = defineStore('aiTrade', {
  state: () => ({
    predictions: {},
    realTimeData: {},
    historicalData: {},
    trainingStatus: null
  }),
  actions: {
    // 集成系统配置模块的方法
    async getSystemConfig() {
      const configStore = getStore(useSystemConfigStore)
      return await withRetry(() => configStore.getSystemConfig())
    },
    async updateSystemConfig(config) {
      const configStore = getStore(useSystemConfigStore)
      return await withRetry(() => configStore.updateSystemConfig(config))
    },

    // 集成其他模块的方法
    async getPrediction(symbol, timeframe = 'daily') {
      console.log('主 store 中的 getPrediction 被调用，参数:', { symbol, timeframe })
      const predictionStore = getStore(usePredictionStore)
      return await withRetry(() => predictionStore.getPrediction(symbol, timeframe))
    },
    async getPredictionMetrics(symbol) {
      const predictionStore = getStore(usePredictionStore)
      return await withRetry(() => predictionStore.getPredictionMetrics(symbol))
    },
    async updatePredictionConfidence(symbol, score) {
      const predictionStore = getStore(usePredictionStore)
      await predictionStore.updateConfidenceScore(symbol, score)
    },
    async getRealTimeData(symbol) {
      const marketDataStore = getStore(useMarketDataStore)
      return await withRetry(() => marketDataStore.getRealTimeData(symbol))
    },
    async getHistoricalData(params) {
      const marketDataStore = getStore(useMarketDataStore)
      return await withRetry(() => marketDataStore.getHistoricalData(params))
    },
    async getMarketSentiment() {
      const sentimentStore = getStore(useMarketSentimentStore)
      return await withRetry(() => sentimentStore.getMarketSentiment())
    },
    async getMarketIndices() {
      const sentimentStore = getStore(useMarketSentimentStore)
      return await withRetry(() => sentimentStore.getMarketIndices())
    },
    async getMarketNews() {
      const sentimentStore = getStore(useMarketSentimentStore)
      return await withRetry(() => sentimentStore.getMarketNews())
    }
  }
})

// 导出主 store 作为默认导出
export default useAITradeStore